import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from api_key import handler as api_key_handler
from api_key import get_api_key 
import urllib
import hmac
import hashlib
import logging


def verify_api_sig(request_url,secret_key,api_sig):
    #verify request
    sig = hmac.new(secret_key,msg=request_url,digestmode=hashlib.sha1).hexdigest()
    logging.info(sig)
    return api_sig == sig
def check_request(request):
    api_key = request.get('api_key')
    api_sig = request.get('api_sig')
    api = get_api_key(api_key)
    if (not api or not api_sig):
        return False
    #remove api_sig
    params = dict([x.split('=')
                   for x in request.query_string.split('&')])
    del params['api_sig']
    #sort
    tmp = params.items()
    tmp.sort()
    
    #rebuild
    query_string = '&'.join([k+ '='+ urllib.quote(str(v))
                            for (k,v) in tmp])
    #verify
    
    return verify_api_sig(request.path + '?' + query_string, api.secret_key, api_sig)
    
class HttpService(webapp.RequestHandler):
    def common(self,handler,method):
        self.response.headers['Content-Type'] = 'application/json; charset=utf-8' 
        if (not check_request(handler.request)):
            self.response.out.write('{."class".: "IncorrectSignatureException" .}')
        self.response.out.write('success')
    def post(self):
        self.common(self,'POST')
    def get(self):
        self.common(self,'GET')


application = webapp.WSGIApplication([
        ('/api_key/add', api_key_handler.AddApiKey),
        ('/bkitmobile/hello', HttpService)
], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()